package daos;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;


/**
 * not thread safe!
 */
public final class HibernateProvider {

    public static HibernateProvider HIBERNATE_PROVIDER;

    private AnnotationConfiguration configuration;
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;


    public static HibernateProvider getInstance() {
        if (HIBERNATE_PROVIDER == null) {
            HIBERNATE_PROVIDER = new HibernateProvider();
        }
        return HIBERNATE_PROVIDER;
    }

    private HibernateProvider() {
        configuration = new AnnotationConfiguration();
    }

    public void registerPersistentClass(Class c) {
        configuration.addAnnotatedClass(c);
    }

    public Session getSession() {
        if (session != null) {
            return session;
        }

        if (sessionFactory == null) {
            sessionFactory = configuration.buildSessionFactory();
        }
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        return session;
    }

    public void commit() {
        session.flush();
        transaction.commit();
    }

    public void rollback() {
        transaction.rollback();
    }


    public void close() {
        session.close();
        session = null;
    }
}
